package sdu.attendancechecker.services;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import sdu.attendancechecker.dto.Attandance;
import sdu.attendancechecker.dto.Subject;
import sdu.attendancechecker.dto.Teacher;
import sdu.attendancechecker.models.SubjectModel;
import sdu.attendancechecker.models.TeacherModel;

public class TeacherService {

	/**
	 * Return Teacher object if exist, otherwise null
	 * 
	 * @param email
	 * @param password
	 * @return
	 */

	public static Teacher login(String email, String password) {
		if (email == null || email.equals("") || password == null
				|| password.equals("")) {
			return null;
		}
		Teacher t = TeacherModel
				.getByLoginAndPassword("email", email, password);
		return t;
	}

	/**
	 * 
	 * @return
	 */
	public static void logout() {
		// TODO - implement {class}.{operation}
		throw new UnsupportedOperationException();
	}

	/**
	 * 
	 * @return
	 */
	public static void forgotPassword() {
		// TODO - implement {class}.{operation}
		throw new UnsupportedOperationException();
	}

	/**
	 * 
	 * @return
	 */
	public static boolean addSubject(Subject s) {
		if (s == null)
			return false;
		return SubjectModel.addSubject(s);
	}

	/**
	 * 
	 * @return
	 */
	public static void updateSubject() {
		// TODO - implement {class}.{operation}
		throw new UnsupportedOperationException();
	}

	/**
	 * 
	 * @return
	 */
	public static void deleteSubject() {
		// TODO - implement {class}.{operation}
		throw new UnsupportedOperationException();
	}

	/**
	 * 
	 * @return
	 */
	public static void updateAttendance() {
		// TODO - implement {class}.{operation}
		throw new UnsupportedOperationException();
	}

	/**
	 * 
	 * @return
	 */
	public static void exportAttendance() {
		// TODO - implement {class}.{operation}
		throw new UnsupportedOperationException();
	}

	/**
	 * 
	 * @return
	 */
	public static void askQuestion() {
		// TODO - implement {class}.{operation}
		throw new UnsupportedOperationException();
	}

	/**
	 * 
	 * @return
	 */
	public static void exportSchedule() {
		// TODO - implement {class}.{operation}
		throw new UnsupportedOperationException();
	}

	/**
	 * 
	 * @return
	 */
	public static void changePassword() {
		// TODO - implement {class}.{operation}
		throw new UnsupportedOperationException();
	}

	/**
	 * Create cookie with teacher_id field
	 * 
	 * @param t
	 * @param maxAge
	 *            cookie's lifetime
	 * @return
	 */

	public static Cookie createCookie(int teacherId, int maxAge) {
		Cookie teacherLoginCookie = new Cookie("teacherId",
				Integer.toString(teacherId));
		teacherLoginCookie.setMaxAge(maxAge);
		return teacherLoginCookie;
	}

	/**
	 * Create cookie with teacher_id field <br>
	 * and cookie's default lifetime 30 minut
	 * 
	 * @param teacherId
	 * @return
	 */
	public static Cookie createCookie(int teacherId) {
		// default max age 30 * 60 = 30 minuts
		int defaultMaxAge = 60 * 30;
		return createCookie(teacherId, defaultMaxAge);
	}

	/**
	 * Search teacherId field from cookie array <br>
	 * 
	 * @param cookie
	 * @return teacherId from cookie, otherwise -1
	 */
	public static int isLogin(Cookie[] cookie) {
		if (cookie == null)
			return -1;
		for (Cookie c : cookie) {
			if (c.getName().equals("teacherId")) {
				try {
					return Integer.parseInt(c.getValue());
				} catch (NumberFormatException ex) {
					return -1;
				}
			}
		}
		return -1;
	}

	public static void export(ArrayList<String> dates, ArrayList<Attandance> att, HttpServletResponse resp) {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("Sample sheet");
		Map<String, Object[]> data = new TreeMap<String, Object[]>();
		Object [] head = new Object[dates.size() + 1];
		head[0] = "Student name";
		for (int i = 1; i<=dates.size(); i++) {
			head[i] = dates.get(i-1);
		}
		data.put("1", head);
		for (int i = 0; i < att.size(); i++) {
			Attandance ta = att.get(i);
			Object[] row = new Object[ta.getAtt().size() + 1];
			row[0] = ta.getStudent();
			for (int j = 1; j <= ta.getAtt().size(); j++) {
				row[j] = ta.getAtt().get(j-1);
			}
			data.put((i + 2) + "", row);
		}
		 
		Set<String> keyset = data.keySet();
		int rownum = 0;
		for (String key : keyset) {
		    Row row = sheet.createRow(rownum++);
		    Object [] objArr = data.get(key);
		    int cellnum = 0;
		    for (Object obj : objArr) {
		        Cell cell = row.createCell(cellnum++);
		        if(obj instanceof Date)
		            cell.setCellValue((Date)obj);
		        else if(obj instanceof Boolean)
		            cell.setCellValue((Boolean)obj);
		        else if(obj instanceof String)
		            cell.setCellValue((String)obj);
		        else if(obj instanceof Double)
		            cell.setCellValue((Double)obj);
		        else if(obj instanceof Integer)
		        	cell.setCellValue((Integer)obj);
		    }
		}
		 
		try {
			resp.setContentType("application/vnd.ms-excel");
			resp.setHeader("Content-Disposition", "attachment; filename=attendance.xls");
		    ServletOutputStream out = resp.getOutputStream();
		            //new FileOutputStream(new File("/excel/attendance.xls"));
		    workbook.write(out);
		    out.close();
		    System.out.println("Excel written successfully..");
		     
		} catch (FileNotFoundException e) {
		    e.printStackTrace();
		} catch (IOException e) {
		    e.printStackTrace();
		}
		
		
	}
	
	/*
	public static ArrayList<Subject> getSortedSubjects(String sortby) {
		SimpleDateFormat sdf = new SimpleDateFormat("");
		java.util.Date date = new java.util.Date();
		String from = sdf.format(date);
		ArrayList<Subject> subjects = null;
		if (sortby == null) {
			sortby = "room";
		}
		return SubjectModel.getSubjectsByTime(sortby, from, 10);
	}
	*/
}
